package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.project.system.domain.SiyuQuery;
import okhttp3.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ZeWu {

    private static final String ZEWU_URL = "https://www.zhichajinkong.com/dataMiddle/api/handle";

    private static final String authorize_URL = "http://82.156.68.252:8000/system/query/accredit/";

    private static final String appId = "3c3ce3eda9ff46b9";

    private static final String appSecret = "283d251782704cdd8ebc0a8e6b5664b5";

    private static final String key = "2c52872066fb89c2ed00c1740ca97b71";

    // Java 实现
    public static String getResult(String proId, SiyuQuery siyuQuery) {
        JSONObject params = new JSONObject();
        if (StringUtils.isNotEmpty(siyuQuery.getName())) {
            params.put("name", encrypt(siyuQuery.getName()));
        }
        if (StringUtils.isNotEmpty(siyuQuery.getCardNo())) {
            params.put("idCard", encrypt(siyuQuery.getCardNo()));
        }
        if (StringUtils.isNotEmpty(siyuQuery.getTel())) {
            params.put("phone", encrypt(siyuQuery.getTel()));
        } else {
            params.put("phone", encrypt(siyuQuery.getMoreKeyword()));
        }
        if ("ZCI102".equals(proId)) {
            params.put("accessoryUrl", authorize_URL + "SQS" + siyuQuery.getQueryId() + ".pdf");
        } else {
            params.put("authorized", "1");
        }

        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(30, TimeUnit.SECONDS).build();
        int timestamp = (int) (System.currentTimeMillis() / 1000);
//        int timestamp = 1755187886;

        String encryptedSecret = Md5Utils.hash(appSecret);
        String sign = Md5Utils.hash(encryptedSecret + timestamp);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), params.toJSONString());
        Request request = new Request.Builder()
                .url(ZEWU_URL)
                .post(body)
                .addHeader("appId", appId)
                .addHeader("proId", proId)
                .addHeader("timestamp", String.valueOf(timestamp))
                .addHeader("sign", sign)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //此处为加解密示例代码，请根据实际情况进行修改，其中key为系统中分配的密钥，请在用户中心实名认证后获取
    public static String encrypt(String data) throws SecurityException {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(hexStringConvertBytes(key), "AES");
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(key.substring(0, 16).getBytes("UTF-8"));
            cipher.init(1, keySpec, paramSpec);
            byte[] result = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception var7) {
            throw new SecurityException("加密失败！");
        }
    }

    private static byte[] hexStringConvertBytes(String data) {
        int length = data.length() / 2;
        byte[] result = new byte[length];
        for (int i = 0; i < length; i++) {
            int first = Integer.parseInt(data.substring(i * 2, i * 2 + 1), 16);
            int second = Integer.parseInt(data.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (first * 16 + second);
        }
        return result;
    }


}
